﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using PH.Model.Commons;
using PH.Data.Commons;
using System.IO;
namespace PH.Logic.Commons
{
    public class FileLogic
    {
        public static void CreateNewFile(FileModel file)
        {
            file.Guid = Guid.NewGuid();
            file.CreatedOn = DateTime.Now;
            FileCommand.CreateNewFile(file);
        }

        public static FileModel GetFile(Guid guid, bool noData = false)
        {
            return FileCommand.GetFile(guid, noData);
        }

        public static FileModel SaveAsposeFile(Aspose.Cells.Workbook wb, Aspose.Cells.FileFormatType excelType,string localName)
        {
            //var filename = string.Format("{0}/{1:yyyyMMddHHmmss.a}", Global.RootFolderPath, DateTime.Now);
            //wb.Save(filename, excelType);
            //var buffer = File.ReadAllBytes(filename);
            var buffer = wb.SaveToStream().ToArray();
            //File.Delete(filename);

            var file = new Model.Commons.FileModel()
            {
                FType = 1,
                Data = buffer,
                Size = buffer.Length,
                LocalName = localName
            };
            FileLogic.CreateNewFile(file);
            return file;
        }

        public static Aspose.Cells.Workbook GetExcel2003(Guid fileGuid)
        {
            var file = FileLogic.GetFile(fileGuid);
            if (file == null)
                throw new Utils.PhException("没有要导入的excel文件");
            MemoryStream ms = new MemoryStream(file.Data);
            Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook();
            workbook.Open(ms, Aspose.Cells.FileFormatType.Excel2003);
            return workbook;
        }

        public static FileModel SaveExcel2003ToFile(Aspose.Cells.Workbook wb, string localName)
        {

            var buffer = wb.SaveToStream().ToArray();
            var file = new Model.Commons.FileModel()
            {
                FType = 1,
                Data = buffer,
                Size = buffer.Length,
                LocalName = localName
            };
            FileLogic.CreateNewFile(file);
            return file;
        }

        public static void UpdateFile(Guid guid, int now, int rows = 0)
        {
            FileCommand.UpdateFile(guid, now, rows);
        }

        public static FileModel GetFileProgressing(Guid guid)
        {
            return FileCommand.GetFileProgressing(guid);
        }
    }
}
